<?php
/**
 * Created by PhpStorm.
 * User: 王 朋
 * Date: 2018/4/16
 * Time: 22:13
 */
namespace application\common\controller;
use application\common\controller\Base;

class Tools extends Base
{
    public static function md5Uniqid() {
        return md5(uniqid().mt_rand(1,100000));
    }

    public function checkPassword($password) {
        if (strlen($password) < 8 || strlen($password) > 25) {
            $this->error("密码长度需在8到25位之间！",$_SERVER['HTTP_REFERER'],'',5);
        }
        // 匹配正则表达式时要添加分隔符
        else if (! preg_match('/[a-zA-Z]/',$password) || ! preg_match('/[!@#$%^&*]/',$password) || ! preg_match('/[0-9]/',$password)) {
            $this->error("密码必须包含数字、字母、特殊字符！",$_SERVER['HTTP_REFERER'],'',5);
        }else {
            return true;
        }
    }

    public static function _sock($url) {
        $host = parse_url($url, PHP_URL_HOST);
        $port = parse_url($url, PHP_URL_PORT);
        $port = $port ? $port : 80;
        $scheme = parse_url($url, PHP_URL_SCHEME);
        $path = parse_url($url, PHP_URL_PATH);
        $query = parse_url($url, PHP_URL_QUERY);
        if ($query) $path .= '?'.$query;
        if ($scheme == 'https') {
            $host = 'ssl://'.$host;
        }
        $fp = fsockopen($host, $port, $err_code, $err_msg, 1);
        if (! $fp) {
            return array('err_code' => $err_code, 'err_msg' => $err_msg);
        }else {
            stream_set_blocking($fp, true);
            stream_set_timeout($fp, 1);
            $header = "GET $path HTTP/1.1\r\n";
            $header .= "Host: $host\r\n";
            $header .= "Connection: close\r\n\r\n";
            fwrite($fp, $header);
            usleep(1000);
            fclose($fp);
            return array('err_code' => 0);
        }
    }

    public static function removeDir($dirName) {
        $handle = @opendir($dirName);
        while(($file = @readdir($handle)) !== false) {
            if ($file != '.' && $file != '..') {
                $dir = $dirName.'/'.$file;
                is_dir($dir) ? static::removeDir($dir) : @unlink($dir);
            }
        }
        closedir($handle);
        return rmdir($dirName);
    }
}